package com.mall.b2c.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mall.b2c.service.LuceneService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mall.b2c.domain.goods.GoodsDomain;
import com.mall.b2c.domain.goods.GoodsTagDomain;
import com.mall.b2c.domain.goods.TagDomain;
import com.mall.b2c.enums.PrescribeType;
import com.mall.b2c.service.GoodsService;
import com.mall.b2c.service.TagService;
import com.mall.b2c.util.JsonDataGridHelper;
import com.mall.common.bean.Message;
import com.mall.common.bean.Message.Type;
import com.mall.common.bean.Pager;
import com.mall.common.bean.SearchFilter;
import com.mall.common.controller.BaseController;
import com.mall.common.enums.MedicalInsuranceType;
import com.mall.common.enums.OperateType;
import com.mall.common.exception.NoticeException;
import com.mall.common.log.Log;
import com.mall.common.util.EnumUtils;
import com.mall.common.util.ResponseUtils;
import com.mall.common.validation.annotation.RequiredFieldValidator;
import com.mall.common.validation.annotation.RequiredStringValidator;
import com.mall.common.validation.annotation.Validations;
import com.mall.common.web.Servlets;

/**
 * 商品
 * @author wangzx
 */
@Controller
@RequestMapping("/admin/b2c/goods")
public class GoodsController  extends BaseController{
	@Resource private GoodsService goodsService; 
	@Resource private TagService tagService;
	@Resource private LuceneService luceneService;
	
	@RequestMapping(value="/checkGoodsCode")
	@ResponseBody
	public String checkGoodsCode(String oldCode, @RequestParam("code")String newCode) {
		if(goodsService.isUnique("code", oldCode, newCode)) {
			return "true";
		} else {
			return "false";
		}
	}
	
	@RequestMapping(value="/checkGoodsHdCode")
	@ResponseBody
	public String checkGoodsHdCode(String oldHdCode, @RequestParam("hdCode")String newHdCode) {
		if(goodsService.isUnique("hdCode", oldHdCode, newHdCode)) {
			return "true";
		} else {
			return "false";
		}
	}
	
	/**
	 * 跳转到列表页面
	 */
	@RequestMapping(value="/list", method=RequestMethod.GET)
	public String list(Model model){


		return "/admin/b2c/goods/list";
	}

	/**
	 * 获取列表信息
	 */
	@RequestMapping(value="/queryData", method=RequestMethod.POST)
	@ResponseBody
	public Pager queryData(Pager pager, HttpServletRequest request){
    	Map<String, Object> filterParams = Servlets.getParametersStartingWith(request);
		List<SearchFilter> filters = SearchFilter.parse(filterParams);
    	pager = goodsService.findPage(pager, filters);
		return JsonDataGridHelper.createJSONData(pager);
    }
	
	@RequestMapping(value="/goodsCategoryTree", method=RequestMethod.GET)
	public String goodsCategoryTree(Model model){
		return "/admin/b2c/goods/goodsCategoryTree";
    }
	
	@RequestMapping(value="/brandGrid", method=RequestMethod.GET)
	public String brandGrid(Model model){
		return "/admin/b2c/goods/brandGrid";
    }
	
    /**
	 * 跳转到新增页面
	 */
	@RequestMapping(value="/add", method=RequestMethod.GET)
	public String input(Model model){
		List<TagDomain> tagList = tagService.getAll();
		model.addAttribute("tagList", tagList);
		model.addAttribute("prescribeTypeList",
				EnumUtils.enumProp2I18nList(PrescribeType.class));
		model.addAttribute("medicalInsuranceTypeList",
				EnumUtils.enumProp2I18nList(MedicalInsuranceType.class));
		return "/admin/b2c/goods/input";
	}
	
	/**
	 * 保存 
	 */
	@Validations(
		requiredStrings = {
			@RequiredStringValidator(fieldName = "code", message = "时空商品编号不允许为空!"),
			@RequiredStringValidator(fieldName = "name", message = "商品名称不允许为空!"),
			@RequiredStringValidator(fieldName = "pyName", message = "拼音码不允许为空!"),
			@RequiredStringValidator(fieldName = "spec", message = "规格不允许为空!"),
			@RequiredStringValidator(fieldName = "marketPrice", message = "建议销售价不允许为空!")
		},
		requiredFields = { 
			@RequiredFieldValidator(fieldName = "goodsCategory.id", message = "商品分类不允许为空!")
		}
	)
	@Log(code="log.goods.add", params={"name","code"}, type=OperateType.goods)
	@RequestMapping(value="/save", method=RequestMethod.POST)
	public String save(GoodsDomain goods, Long[] tagIds, Model model){
		Message message = goodsService.saveGoods(goods, tagIds);
		if(message.getType() == Type.ERROR) {
			throw new NoticeException(message.getContent());
		}
		model.addAttribute("parentMenuNo", "b2c_goods_list");
		model.addAttribute("refresh", "true");
		//异步更新索引
		luceneService.updateIndexGoods(new Long[]{goods.getId()});
		return CLOSEANRELOAPARENT;	
    }
    
	
	/**
	 * 上传图片
	 */
	@Validations(
		requiredFields = { 
			@RequiredFieldValidator(fieldName = "id", message = "ID非法!")
		}
	)
	@RequestMapping(value="/uploadPic", method=RequestMethod.GET)
	public String uploadPic(Long id, Model model) {
		GoodsDomain goods = goodsService.find(id);
    	model.addAttribute("goods", goods);
		return "/admin/b2c/goods/uploadPic";
	}
	
	/**
	 * 修改上传图片
	 * @param goods
	 * @param model
	 * @return
	 */
	@Log(code="log.goods.upload", params={"id"}, type=OperateType.goods)
	@RequestMapping(value="/uploadPic", method=RequestMethod.POST)
	public String uploadPic(GoodsDomain goods, Model model){
		Message message = goodsService.updatePic(goods);
		if(message.getType() == Type.ERROR) {
			throw new NoticeException(message.getContent());
		}
		model.addAttribute("parentMenuNo", "b2c_goods_list");
		model.addAttribute("refresh", "true");
		return CLOSEANRELOAPARENT;	
	}
	
	/**
	 * 编辑 
	 */
	@Validations(
		requiredFields = { 
			@RequiredFieldValidator(fieldName = "id", message = "ID非法!")
		}
	)
	@RequestMapping(value="/edit", method=RequestMethod.GET)
	public String edit(Long id, Model model){
		GoodsDomain goods = goodsService.find(id);
    	model.addAttribute("goods", goods);
    	List<TagDomain> tagList = tagService.getAll();
    	model.addAttribute("tagList", tagList);
    	
    	List<Long> goodsTagList = new ArrayList<Long>();
    	Set<GoodsTagDomain> goodsTags = goods.getGoodsTags();
    	if(!CollectionUtils.isEmpty(goodsTags)) {
    		for(GoodsTagDomain goodsTag : goodsTags) {
    			if(goodsTag.getTag() != null) {
    				goodsTagList.add(goodsTag.getTag().getId());
    			}
    		}
    	}
    	model.addAttribute("goodsTagList", goodsTagList);
    	model.addAttribute("prescribeTypeList",
				EnumUtils.enumProp2I18nList(PrescribeType.class));
		model.addAttribute("medicalInsuranceTypeList",
				EnumUtils.enumProp2I18nList(MedicalInsuranceType.class));
		return "/admin/b2c/goods/input";
	}
	
	/**
	 * 修改
	 */
	@Validations(
		requiredStrings = {
				@RequiredStringValidator(fieldName = "code", message = "时空商品编号不允许为空!"),
				@RequiredStringValidator(fieldName = "name", message = "商品名称不允许为空!"),
				@RequiredStringValidator(fieldName = "pyName", message = "拼音码不允许为空!"),
				@RequiredStringValidator(fieldName = "spec", message = "规格不允许为空!"),
				@RequiredStringValidator(fieldName = "marketPrice", message = "建议销售价不允许为空!")
		},
		requiredFields = { 
			@RequiredFieldValidator(fieldName = "id", message = "ID非法!"),
			@RequiredFieldValidator(fieldName = "goodsCategory.id", message = "商品分类不允许为空!")
		}
	)
	@Log(code="log.goods.edit", params={"name","id","code"}, type=OperateType.goods)
	@RequestMapping(value="/update", method=RequestMethod.POST)
	public String update(GoodsDomain goods, Long[] tagIds, Model model){
		Message message = goodsService.updateGoods(goods, tagIds);
		if(message.getType() == Type.ERROR) {
			throw new NoticeException(message.getContent());
		}
		model.addAttribute("parentMenuNo", "b2c_goods_list");
		model.addAttribute("refresh", "true");
		//异步更新索引
		luceneService.updateIndexGoods(new Long[]{goods.getId()});
		return CLOSEANRELOAPARENT;	
	}
	
	 /**
	 * 商品上架
	 */
	@Validations(
		requiredFields = {
			@RequiredFieldValidator(fieldName = "ids", message = "ids非法")	
		}
	)
	@Log(code="log.goods.upmarket", params={"ids"}, type=OperateType.marketable)
	@RequestMapping(value="/upMarket", method=RequestMethod.POST)
	@ResponseBody
	public String upMarket(Long[] ids, HttpServletResponse response) {
		goodsService.upMarket(ids);
		//异步更新索引
		luceneService.updateIndexGoods(ids);
		return ResponseUtils.renderJSON(successMessage, response);
	}
	
	 /**
	 * 商品下架
	 */
	@Validations(
		requiredFields = {
			@RequiredFieldValidator(fieldName = "ids", message = "ids非法")	
		}
	)
	@Log(code="log.goods.downmarket", params={"ids"}, type=OperateType.marketable)
	@RequestMapping(value="/downMarket", method=RequestMethod.POST)
	@ResponseBody
	public String downMarket(Long[] ids, HttpServletResponse response) {
		goodsService.downMarket(ids);
		//异步更新索引
		luceneService.updateIndexGoods(ids);
		return ResponseUtils.renderJSON(successMessage, response);
	}
}


